package com.example.app3_1;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ProfileFragment extends Fragment {
    private static final String ARG_USERNAME = "username";
    private static final String ARG_INTEREST = "interest";

    private String username;
    private String interest;
    private TextView tvEmail, tvInterest;
    private static final int REQUEST_IMAGE_PICK = 1001;
    private static final int REQUEST_PERMISSION = 1002;
    private ImageView ivAvatar;

    public static ProfileFragment newInstance(String username, String interest) {
        ProfileFragment fragment = new ProfileFragment();
        Bundle args = new Bundle();
        args.putString(ARG_USERNAME, username);
        args.putString(ARG_INTEREST, interest);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            username = getArguments().getString(ARG_USERNAME);
            interest = getArguments().getString(ARG_INTEREST);
        }

        // 从Activity获取最新兴趣数据
        if (getActivity() instanceof HomeActivity) {
            String latestInterest = ((HomeActivity) getActivity()).getInterest();
            if (latestInterest != null && !latestInterest.isEmpty()) {
                interest = latestInterest;
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);

        try {
            // 初始化所有视图
            tvEmail = view.findViewById(R.id.tv_email);
            tvInterest = view.findViewById(R.id.tv_interest);
            ivAvatar = view.findViewById(R.id.iv_avatar);
            Button btnSelectInterest = view.findViewById(R.id.btn_select_interest);
            Button btnLogout = view.findViewById(R.id.btn_logout);
            Button btnMyBooks = view.findViewById(R.id.btn_my_books);
            Button btnGpsMonitor = view.findViewById(R.id.btn_gps_monitor);

            // 检查视图是否成功初始化
            if (tvEmail == null) throw new NullPointerException("tv_email not found");
            if (tvInterest == null) throw new NullPointerException("tv_interest not found");
            if (ivAvatar == null) throw new NullPointerException("iv_avatar not found");
            if (btnSelectInterest == null) throw new NullPointerException("btn_select_interest not found");
            if (btnLogout == null) throw new NullPointerException("btn_logout not found");
            if (btnMyBooks == null) throw new NullPointerException("btn_my_books not found");
            if (btnGpsMonitor == null) throw new NullPointerException("btn_gps_monitor not found");

            // 设置用户信息
            updateDisplay();

            // 加载用户头像
            loadUserAvatar();

            // 设置头像点击事件
            ivAvatar.setOnClickListener(v -> changeAvatar());

            // 设置按钮点击事件
            btnSelectInterest.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), InterestSelectionActivity.class);
                startActivityForResult(intent, 1);
            });

            btnGpsMonitor.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), GpsActivity.class);
                startActivity(intent);
            });

            btnMyBooks.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), BookListActivity.class);
                intent.putExtra("username", username);
                startActivity(intent);
            });

            btnLogout.setOnClickListener(v -> {
                if (getActivity() instanceof HomeActivity) {
                    ((HomeActivity) getActivity()).showLogoutDialog();
                }
            });

        } catch (NullPointerException e) {
            // 打印详细的错误信息
            Log.e("ProfileFragment", "View initialization failed: " + e.getMessage());
            Toast.makeText(getContext(), "界面初始化失败，请检查布局文件", Toast.LENGTH_LONG).show();
        }

        return view;
    }

    private File getAvatarFile(String username) {
        // 使用应用私有目录，确保数据安全
        File avatarsDir = new File(requireContext().getFilesDir(), "avatars");
        if (!avatarsDir.exists()) {
            avatarsDir.mkdirs();
        }

        // 使用用户名作为文件名，确保用户隔离
        String filename = "avatar_" + username.hashCode() + ".jpg";
        return new File(avatarsDir, filename);
    }

    private void loadUserAvatar() {
        if (username == null || username.isEmpty()) return;

        File avatarFile = getAvatarFile(username);
        if (avatarFile.exists()) {
            // 加载保存的头像
            Bitmap bitmap = BitmapFactory.decodeFile(avatarFile.getAbsolutePath());
            if (bitmap != null) {
                ivAvatar.setImageBitmap(bitmap);
            }
        }
        // 如果文件不存在，保持默认头像
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("ProfileFragment", "onResume");
        // 每次Fragment可见时都更新数据
        if (getActivity() instanceof HomeActivity) {
            String latestInterest = ((HomeActivity) getActivity()).getInterest();
            if (latestInterest != null && !latestInterest.isEmpty()) {
                interest = latestInterest;
                updateDisplay();
            }
        }
    }

    private void updateDisplay() {
        if (tvEmail != null) {
            tvEmail.setText("邮箱：" + username);
        }
        if (tvInterest != null) {
            tvInterest.setText("兴趣：" + interest);
        }
    }

    /**
     * 更新兴趣显示 - 添加空检查
     */
    public void updateInterest(String newInterest) {
        this.interest = newInterest;
        // 只有在视图存在时才更新UI
        if (tvInterest != null && isAdded()) {
            updateDisplay();
        }
    }

    private void changeAvatar() {
        // 检查权限
        if (ContextCompat.checkSelfPermission(requireContext(),
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            // 解释为什么需要权限
            if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                // 显示解释对话框
                new AlertDialog.Builder(requireContext())
                        .setTitle("需要存储权限")
                        .setMessage("需要存储权限以选择图片作为头像")
                        .setPositiveButton("确定", (dialog, which) -> {
                            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                    REQUEST_PERMISSION);
                        })
                        .setNegativeButton("取消", null)
                        .show();
            } else {
                // 直接请求权限
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_PERMISSION);
            }
        } else {
            // 已有权限，打开相册
            openImagePicker();
        }
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限 granted，打开相册
                openImagePicker();
            } else {
                // 权限 denied，显示提示
                Toast.makeText(requireContext(), "需要存储权限才能选择头像", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 打开图片选择器
    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_IMAGE_PICK);
    }

    // 处理图片选择结果
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1) {
            // 兴趣选择结果处理
            if (resultCode == Activity.RESULT_OK && data != null) {
                String newInterest = data.getStringExtra("interest");
                if (newInterest != null) {
                    // 通知HomeActivity更新所有Fragment的兴趣显示 - 添加存在性检查
                    if (getActivity() instanceof HomeActivity && isAdded()) {
                        ((HomeActivity) getActivity()).updateHomeFragmentInterest(newInterest);
                    }
                }
            }
        } else if (requestCode == REQUEST_IMAGE_PICK) {
            // 头像选择结果处理
            if (resultCode == Activity.RESULT_OK && data != null) {
                Uri selectedImageUri = data.getData();
                if (selectedImageUri != null) {
                    // 处理选择的图片
                    handleSelectedImage(selectedImageUri);
                }
            } else {
                // 用户取消选择，保持原有头像
                Toast.makeText(requireContext(), "取消选择头像", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 处理选择的图片
    private void handleSelectedImage(Uri imageUri) {
        try {
            // 获取图片路径
            String imagePath = getImagePathFromUri(imageUri);
            if (imagePath == null) {
                Toast.makeText(requireContext(), "图片选择失败", Toast.LENGTH_SHORT).show();
                return;
            }

            // 压缩并保存图片
            Bitmap bitmap = decodeSampledBitmapFromPath(imagePath, 200, 200);
            if (bitmap != null) {
                // 删除旧头像文件
                File oldAvatarFile = getAvatarFile(username);
                if (oldAvatarFile.exists()) {
                    oldAvatarFile.delete();
                }

                // 保存新头像
                File newAvatarFile = getAvatarFile(username);
                saveBitmapToFile(bitmap, newAvatarFile);

                // 更新界面
                ivAvatar.setImageBitmap(bitmap);
                Toast.makeText(requireContext(), "头像更换成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(requireContext(), "图片处理失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "头像更换失败", Toast.LENGTH_SHORT).show();
        }
    }

    // 从Uri获取图片路径
    private String getImagePathFromUri(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = requireContext().getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String path = cursor.getString(column_index);
            cursor.close();
            return path;
        }
        return uri.getPath(); // 备用方案
    }

    // 压缩图片
    private Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) {
        // 首先获取图片尺寸
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        // 计算采样率
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // 解码图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }

    // 计算采样率
    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    // 保存Bitmap到文件
    private void saveBitmapToFile(Bitmap bitmap, File file) {
        try (FileOutputStream out = new FileOutputStream(file)) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}